import { Router } from 'express';
import { body, param, query } from 'express-validator';
import { ArticleController } from '../controllers/article.controller';
import { authMiddleware } from '../middlewares/auth.middleware';
import { validateMiddleware } from '../middlewares/validate.middleware';

const router = Router();
const articleController = ArticleController.getInstance();

// 创建文章
router.post(
    '/',
    authMiddleware,
    [
        body('title')
            .notEmpty().withMessage('标题不能为空')
            .isLength({ max: 100 }).withMessage('标题长度不能超过100个字符'),
        body('content')
            .notEmpty().withMessage('内容不能为空')
            .isLength({ min: 10 }).withMessage('内容长度不能少于10个字符'),
        body('isPublic')
            .optional()
            .isBoolean().withMessage('isPublic必须是布尔值')
    ],
    validateMiddleware,
    articleController.createArticle
);

// 获取指定文章
router.get(
    '/:id',
    [
        param('id')
            .isInt().withMessage('文章ID必须是整数')
    ],
    validateMiddleware,
    articleController.getArticleById
);

// 更新文章
router.put(
    '/:id',
    authMiddleware,
    [
        param('id')
            .isInt().withMessage('文章ID必须是整数'),
        body('title')
            .optional()
            .isLength({ max: 100 }).withMessage('标题长度不能超过100个字符'),
        body('content')
            .optional()
            .isLength({ min: 10 }).withMessage('内容长度不能少于10个字符'),
        body('isPublic')
            .optional()
            .isBoolean().withMessage('isPublic必须是布尔值')
    ],
    validateMiddleware,
    articleController.updateArticle
);

// 删除文章
router.delete(
    '/:id',
    authMiddleware,
    [
        param('id')
            .isInt().withMessage('文章ID必须是整数')
    ],
    validateMiddleware,
    articleController.deleteArticle
);

// 获取用户的文章列表
router.get(
    '/author/:authorId',
    authMiddleware,
    [
        param('authorId')
            .isInt().withMessage('用户ID必须是整数'),
        query('pageNo')
            .optional()
            .isInt({ min: 1 }).withMessage('页码必须是大于0的整数'),
        query('pageSize')
            .optional()
            .isInt({ min: 1, max: 100 }).withMessage('每页数量必须是1-100之间的整数')
    ],
    validateMiddleware,
    articleController.getArticlesByAuthor
);

// 获取公开文章列表
router.get(
    '/',
    [
        query('pageNo')
            .optional()
            .isInt({ min: 1 }).withMessage('页码必须是大于0的整数'),
        query('pageSize')
            .optional()
            .isInt({ min: 1, max: 100 }).withMessage('每页数量必须是1-100之间的整数')
    ],
    validateMiddleware,
    articleController.getPublicArticles
);

// 点赞或取消点赞
router.post(
    '/:id/like',
    authMiddleware,
    [
        param('id')
            .isInt().withMessage('文章ID必须是整数'),
        body('action')
            .isIn(['like', 'unlike']).withMessage('操作类型必须是 like 或 unlike')
    ],
    validateMiddleware,
    articleController.toggleLike
);

export default router; 